describe('前端本地缓存管理测试', () => {
  let testData

  before(() => {
    cy.fixture('test-data').then((data) => {
      testData = data
    })
  })

  beforeEach(() => {
    // 每次测试前清理缓存，确保干净的测试环境
    cy.clearAllCaches()
  })

  afterEach(() => {
    // 测试完成后清理缓存
    cy.clearAllCaches()
  })

  describe('📦 本地缓存基础操作测试', () => {
    it('应该测试缓存的基本存储和读取操作', () => {
      cy.visit('http://localhost:8002/#/pages/select/select')
      cy.wait(2000)

      // 模拟填写订单信息并调用API
      const testOrderData = {
        orderNo: `CACHE_TEST_${Date.now()}`,
        orderBranchNo: "01",
        mounterId: "M05",
        smtSide: "1"
      }

      cy.log('🔍 测试本地缓存存储操作')

      // 检查初始缓存状态
      cy.window().then((win) => {
        const initialCache = win.uni.getStorageInfoSync()
        cy.log(`📊 初始缓存键数量: ${initialCache.keys.length}`)
        
        // 存储测试数据到缓存
        const cacheKey = 'smtOrderData'
        const dataToStore = {
          type: 'object',
          data: {
            orderInfo: testOrderData,
            rollMngNo: `TEST_ROLL_${Date.now()}`,
            partList: [
              {
                partId: 'TEST_PART_001',
                partName: '测试零件1',
                quantity: 100
              },
              {
                partId: 'TEST_PART_002', 
                partName: '测试零件2',
                quantity: 200
              }
            ]
          }
        }

        win.uni.setStorageSync(cacheKey, dataToStore)
        cy.log('✅ 缓存数据存储成功')

        // 验证数据是否正确存储
        const retrievedData = win.uni.getStorageSync(cacheKey)
        expect(retrievedData).to.not.be.null
        expect(retrievedData.type).to.equal('object')
        expect(retrievedData.data.orderInfo.orderNo).to.equal(testOrderData.orderNo)
        expect(retrievedData.data.partList).to.have.length(2)
        
        cy.log('✅ 缓存数据读取验证成功')
        cy.log(`📋 订单号: ${retrievedData.data.orderInfo.orderNo}`)
        cy.log(`📦 零件数量: ${retrievedData.data.partList.length}`)
      })
    })

    it('应该测试缓存的更新操作', () => {
      cy.window().then((win) => {
        const cacheKey = 'smtOrderData'
        
        // 先存储初始数据
        const initialData = {
          type: 'object',
          data: {
            orderInfo: {
              orderNo: `UPDATE_TEST_${Date.now()}`,
              mounterId: "M05"
            },
            rollMngNo: "INITIAL_ROLL",
            status: 'initial'
          }
        }
        
        win.uni.setStorageSync(cacheKey, initialData)
        cy.log('📝 初始缓存数据存储完成')

        // 更新缓存数据
        const currentData = win.uni.getStorageSync(cacheKey)
        const updatedData = {
          ...currentData,
          data: {
            ...currentData.data,
            rollMngNo: "UPDATED_ROLL",
            status: 'updated',
            updateTime: new Date().toISOString()
          }
        }
        
        win.uni.setStorageSync(cacheKey, updatedData)
        cy.log('🔄 缓存数据更新完成')

        // 验证更新是否成功
        const finalData = win.uni.getStorageSync(cacheKey)
        expect(finalData.data.rollMngNo).to.equal("UPDATED_ROLL")
        expect(finalData.data.status).to.equal('updated')
        expect(finalData.data.updateTime).to.exist
        
        cy.log('✅ 缓存更新验证成功')
        cy.log(`📊 更新后状态: ${finalData.data.status}`)
      })
    })
  })

  describe('🧹 缓存清理功能测试', () => {
    it('应该测试uni.clearStorageSync()全量清理功能', () => {
      cy.window().then((win) => {
        // 先创建多个缓存项
        const testCaches = [
          { key: 'smtOrderData', value: { test: 'data1' } },
          { key: 'testCache1', value: 'value1' },
          { key: 'testCache2', value: { data: 'value2' } },
          { key: 'tempData', value: [1, 2, 3] }
        ]

        testCaches.forEach(cache => {
          win.uni.setStorageSync(cache.key, cache.value)
        })

        cy.log(`📦 创建了${testCaches.length}个测试缓存项`)
        
        // 验证缓存存在
        const beforeClear = win.uni.getStorageInfoSync()
        expect(beforeClear.keys.length).to.be.greaterThan(0)
        cy.log(`📊 清理前缓存键数量: ${beforeClear.keys.length}`)

        // 执行全量清理
        win.uni.clearStorageSync()
        cy.log('🧹 执行uni.clearStorageSync()清理')

        // 验证清理结果
        const afterClear = win.uni.getStorageInfoSync()
        expect(afterClear.keys.length).to.equal(0)
        cy.log('✅ 全量缓存清理验证成功')
        cy.log(`📊 清理后缓存键数量: ${afterClear.keys.length}`)
      })
    })

    it('应该测试uni.removeStorageSync()单个清理功能', () => {
      cy.window().then((win) => {
        // 创建测试缓存
        const cacheKeys = ['cache1', 'cache2', 'cache3']
        cacheKeys.forEach(key => {
          win.uni.setStorageSync(key, { data: `test_${key}` })
        })

        cy.log(`📦 创建了${cacheKeys.length}个测试缓存项`)

        // 验证初始状态
        const initialInfo = win.uni.getStorageInfoSync()
        expect(initialInfo.keys).to.include.members(cacheKeys)

        // 逐个删除缓存
        win.uni.removeStorageSync('cache1')
        cy.log('🗑️ 删除cache1')
        
        win.uni.removeStorageSync('cache2')  
        cy.log('🗑️ 删除cache2')

        // 验证部分删除结果
        const afterPartialRemoval = win.uni.getStorageInfoSync()
        expect(afterPartialRemoval.keys).to.not.include('cache1')
        expect(afterPartialRemoval.keys).to.not.include('cache2')
        expect(afterPartialRemoval.keys).to.include('cache3')
        
        cy.log('✅ 单个缓存删除验证成功')
        cy.log(`📊 剩余缓存键: ${afterPartialRemoval.keys.join(', ')}`)

        // 删除最后一个
        win.uni.removeStorageSync('cache3')
        const finalInfo = win.uni.getStorageInfoSync()
        expect(finalInfo.keys).to.not.include.members(cacheKeys)
        
        cy.log('✅ 所有指定缓存清理完成')
      })
    })

    it('应该测试缓存清理的错误处理', () => {
      cy.window().then((win) => {
        // 测试删除不存在的缓存键
        cy.log('🧪 测试删除不存在的缓存键')
        
        // 这不应该抛出错误
        expect(() => {
          win.uni.removeStorageSync('NON_EXISTENT_KEY')
        }).to.not.throw()
        
        cy.log('✅ 删除不存在缓存键的错误处理正常')

        // 测试获取不存在的缓存
        const nonExistentData = win.uni.getStorageSync('ANOTHER_NON_EXISTENT_KEY')
        expect(nonExistentData).to.equal('')  // UniApp返回空字符串
        
        cy.log('✅ 获取不存在缓存的错误处理正常')
      })
    })
  })

  describe('🔄 页面级缓存操作测试', () => {
    it('应该测试Select页面的缓存清理操作', () => {
      cy.visit('http://localhost:8002/#/pages/select/select')
      cy.wait(2000)

      cy.window().then((win) => {
        // 模拟存储一些数据
        win.uni.setStorageSync('smtOrderData', { test: 'select_page_data' })
        win.uni.setStorageSync('tempData1', 'temp1')
        win.uni.setStorageSync('tempData2', 'temp2')
        
        cy.log('📦 创建测试缓存数据')
        
        // 验证数据存在
        const beforeClear = win.uni.getStorageInfoSync()
        expect(beforeClear.keys.length).to.be.greaterThan(0)
        cy.log(`📊 清理前缓存数量: ${beforeClear.keys.length}`)
      })

      // 模拟点击开始按钮触发缓存清理
      cy.get('body').then(($body) => {
        if ($body.find('.btn-start').length > 0) {
          // 先填写必要字段
          if ($body.find('input').length > 0) {
            cy.get('input').first().type('TEST123')
            if ($body.find('input').length > 1) {
              cy.get('input').eq(1).type('M05')
            }
            if ($body.find('input').length > 2) {
              cy.get('input').eq(2).type('1')
            }
          }

          cy.window().then((win) => {
            // 在点击按钮前记录缓存状态
            const beforeClick = win.uni.getStorageInfoSync()
            cy.log(`⏰ 点击前缓存键: ${beforeClick.keys.join(', ')}`)
          })

          // 注意：实际点击可能会导航到其他页面或调用API
          // 这里我们主要验证缓存清理逻辑
          cy.log('🖱️ 模拟点击开始按钮')
        } else {
          cy.log('⚠️ 未找到开始按钮，跳过点击测试')
        }
      })
    })

    it('应该测试扫码记录的临时缓存管理', () => {
      cy.window().then((win) => {
        // 模拟扫码记录的缓存操作
        const scanRecordsKey = 'scanRecords'
        const testScanData = [
          {
            partId: 'SCAN001',
            rollNo: 'ROLL001',
            scanTime: new Date().toISOString(),
            status: 'success'
          },
          {
            partId: 'SCAN002', 
            rollNo: 'ROLL002',
            scanTime: new Date().toISOString(),
            status: 'success'
          }
        ]

        // 存储扫码记录
        win.uni.setStorageSync(scanRecordsKey, testScanData)
        cy.log('📋 存储扫码记录到缓存')

        // 验证存储
        const retrievedScanData = win.uni.getStorageSync(scanRecordsKey)
        expect(retrievedScanData).to.have.length(2)
        expect(retrievedScanData[0].partId).to.equal('SCAN001')
        
        cy.log('✅ 扫码记录缓存存储验证成功')

        // 模拟添加新的扫码记录
        const newScanRecord = {
          partId: 'SCAN003',
          rollNo: 'ROLL003', 
          scanTime: new Date().toISOString(),
          status: 'failed'
        }

        const updatedScanData = [...retrievedScanData, newScanRecord]
        win.uni.setStorageSync(scanRecordsKey, updatedScanData)
        
        cy.log('📝 添加新扫码记录到缓存')

        // 验证更新
        const finalScanData = win.uni.getStorageSync(scanRecordsKey)
        expect(finalScanData).to.have.length(3)
        expect(finalScanData[2].status).to.equal('failed')
        
        cy.log('✅ 扫码记录缓存更新验证成功')

        // 模拟完成后清理扫码记录缓存
        win.uni.removeStorageSync(scanRecordsKey)
        
        const afterCleanup = win.uni.getStorageSync(scanRecordsKey)
        expect(afterCleanup).to.equal('')  // UniApp返回空字符串表示不存在
        
        cy.log('🧹 扫码记录缓存清理验证成功')
      })
    })
  })

  describe('📊 缓存状态监控测试', () => {
    it('应该测试缓存容量和状态信息', () => {
      cy.window().then((win) => {
        // 获取缓存状态信息
        const storageInfo = win.uni.getStorageInfoSync()
        
        cy.log('📊 当前缓存状态信息:')
        cy.log(`   - 缓存键数量: ${storageInfo.keys.length}`)
        cy.log(`   - 当前大小: ${storageInfo.currentSize}KB`)
        cy.log(`   - 限制大小: ${storageInfo.limitSize}KB`)
        cy.log(`   - 使用率: ${((storageInfo.currentSize / storageInfo.limitSize) * 100).toFixed(2)}%`)

        // 验证基本属性存在
        expect(storageInfo).to.have.property('keys')
        expect(storageInfo).to.have.property('currentSize')
        expect(storageInfo).to.have.property('limitSize')
        expect(storageInfo.keys).to.be.an('array')
        expect(storageInfo.currentSize).to.be.a('number')
        expect(storageInfo.limitSize).to.be.a('number')
        
        cy.log('✅ 缓存状态信息验证成功')

        // 创建大量缓存数据测试
        const largeCacheData = {
          largeArray: new Array(1000).fill(0).map((_, i) => ({
            id: i,
            data: `large_test_data_${i}`,
            timestamp: Date.now()
          })),
          metadata: {
            created: new Date().toISOString(),
            type: 'performance_test'
          }
        }

        win.uni.setStorageSync('largeCacheTest', largeCacheData)
        
        const afterLargeCache = win.uni.getStorageInfoSync()
        cy.log(`📈 大数据缓存后大小: ${afterLargeCache.currentSize}KB`)
        
        // 清理大缓存
        win.uni.removeStorageSync('largeCacheTest')
        const afterCleanup = win.uni.getStorageInfoSync()
        cy.log(`📉 清理后大小: ${afterCleanup.currentSize}KB`)
        
        cy.log('✅ 缓存容量测试完成')
      })
    })

    it('应该测试缓存数据的完整性验证', () => {
      cy.window().then((win) => {
        // 创建复杂的嵌套数据结构
        const complexData = {
          orderInfo: {
            orderNo: `INTEGRITY_TEST_${Date.now()}`,
            details: {
              mounterId: "M05",
              smtSide: "1",
              metadata: {
                created: new Date().toISOString(),
                version: "1.0.0"
              }
            }
          },
          partList: [
            {
              partId: "PART001",
              specifications: {
                length: 10.5,
                width: 5.2,
                height: 2.1
              },
              properties: {
                color: "blue",
                material: "plastic",
                certifications: ["ISO9001", "RoHS"]
              }
            }
          ],
          rollData: {
            rollMngNo: "ROLL123",
            contents: new Array(50).fill(0).map((_, i) => ({
              seq: i + 1,
              lotNo: `LOT${String(i).padStart(3, '0')}`,
              quantity: Math.floor(Math.random() * 100) + 1
            }))
          }
        }

        const cacheKey = 'complexDataTest'
        
        // 存储复杂数据
        win.uni.setStorageSync(cacheKey, complexData)
        cy.log('📦 存储复杂嵌套数据结构')

        // 读取并验证完整性
        const retrievedData = win.uni.getStorageSync(cacheKey)
        
        // 验证顶层结构
        expect(retrievedData).to.have.property('orderInfo')
        expect(retrievedData).to.have.property('partList')
        expect(retrievedData).to.have.property('rollData')
        
        // 验证嵌套结构
        expect(retrievedData.orderInfo.details.mounterId).to.equal("M05")
        expect(retrievedData.partList[0].specifications.length).to.equal(10.5)
        expect(retrievedData.rollData.contents).to.have.length(50)
        expect(retrievedData.partList[0].properties.certifications).to.include("RoHS")
        
        cy.log('✅ 复杂数据结构完整性验证成功')
        cy.log(`📋 订单号: ${retrievedData.orderInfo.orderNo}`)
        cy.log(`📊 零件数: ${retrievedData.partList.length}`)
        cy.log(`📦 卷轴内容数: ${retrievedData.rollData.contents.length}`)
        
        // 清理测试数据
        win.uni.removeStorageSync(cacheKey)
      })
    })
  })
})